package deviceid

import (
	"errors"
	"os"
	"strings"

	"gitee.com/myzero1/gotool/z1crypto"
	"gitee.com/z1gotool/z1err"
	"github.com/yumaojun03/dmidecode"
)

func GetId(key ...string) (data string, err error) {
	defer z1err.Handle(&err)

	keyNew := `gitee.com/z1gotool/deviceid`
	if len(key) > 0 {
		keyNew = key[0]
	}

	id, err := getCpuId()
	z1err.Check(err)

	text := id + keyNew
	data = z1crypto.MD5Encode(text)

	return
}

func GetIdText() (data string, err error) {
	data, err = getCpuId()
	return
}

func getCpuId() (id string, err error) {
	defer z1err.Handle(&err)

	dmi, err := dmidecode.New()
	if err != nil {
		// head -1 /proc/self/cgroup|cut -d/ -f3|cut -c1-12
		id, err = getDockerContainerId()
		z1err.Check(err)
	} else {
		infos, err1 := dmi.Processor()
		z1err.Check(err1)

		for i := range infos {
			if infos[i].ID.String() != `` {
				id = infos[i].ID.String()
				id = strings.ReplaceAll(id, " ", "")
				return
			}
		}

		err = errors.New(`not found cpu id`)
	}

	return
}

func getDockerContainerId() (id string, err error) {
	defer z1err.Handle(&err)

	fileName := `/proc/self/cgroup`
	// fileName := `t`
	content, err := os.ReadFile(fileName)
	z1err.Check(err)
	str := string(content)

	info := strings.Split(str, "\n")
	line := info[0]
	info1 := strings.Split(line, "/")
	id = info1[2]
	id = string(id[0:16])
	id = strings.ToUpper(id)

	return
}
